package org.mspring.mlog.web.module.web;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mspring.mlog.entity.Catalog;
import org.mspring.mlog.entity.Post;
import org.mspring.mlog.entity.constants.PageNames;
import org.mspring.mlog.service.CatalogService;
import org.mspring.mlog.service.PostService;
import org.mspring.platform.dao.Page;
import org.mspring.platform.web.freemarker.FreemarkerVariableNames;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 根据分类归档文章
 *
 * @author Gao Youbo
 * @since 2013-2-28
 */
@Widget
@RequestMapping("/post")
public class Web_ArchiveCatalogWidget extends Web_AbstractWidget {
    @Autowired
    private PostService postService;

    @Autowired
    private CatalogService catalogService;

    @RequestMapping("/catalog")
    public String archiveByCatalog(@RequestParam(defaultValue = "0") long catalog, @RequestParam(defaultValue = "1") int page, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        if (catalog < 1) {
            response.sendError(404);
            return null;
        }
        Page<Post> postPage = new Page<>();
        postPage.setPageNo(page);
        postService.listByCatalog(postPage, catalog);
        model.addAttribute(FreemarkerVariableNames.POST_PAGE, postPage);

        // 这个catalogId是判断是否是分类归档的依据
        model.addAttribute("catalogId", catalog);
        model.addAttribute("catalog", catalogService.get(catalog));

        // 设置当前页
        Catalog cat = catalogService.get(catalog);
        model.addAttribute(FreemarkerVariableNames.CATALOG_ARCHIVE_NAME, cat.getName());
        setCurrnetPage(model, PageNames.CATALOG_ARCHIVE);
        return "skin:/archiveCatalog";
    }
}
